package cn.mapway.ib.client.rpc;

import cn.mapway.ib.share.model.common.ApiResult;
import cn.mapway.ib.share.model.dir.DirFile;
import com.google.gwt.core.client.Callback;
import elemental2.core.Global;
import elemental2.dom.Event;
import elemental2.dom.XMLHttpRequest;
import jsinterop.base.Js;

/**
 * rpc 接口调用
 */
public class AppInstallProxy {

    public static void listdir(String dir, Callback<ApiResult<DirFile[]>, String> callback) {
        if (dir == null) {
            dir = "";
        }
        getAs("/dir/list?dir=" + dir, "", callback);
    }

    public static void listfiles(String dir, Callback<ApiResult<DirFile[]>, String> callback) {
        if (dir == null) {
            dir = "";
        }
        getAs("/dir/files?dir=" + dir, "", callback);
    }

    public static <T> void getAs(String url, String data, Callback<T, String> callback) {
        XMLHttpRequest request = new XMLHttpRequest();
        request.open("get", url);
        request.onreadystatechange = p0 -> {
            if (request.readyState == XMLHttpRequest.DONE) {
                if (callback != null) {
                    if (request.status == 200) {
                        Object obj = Global.JSON.parse(request.responseText);
                        callback.onSuccess(Js.uncheckedCast(obj));
                    } else {
                        callback.onFailure(request.responseText);
                    }
                }
            }
            return true;
        };
        request.send(data);
    }

    public static void get(String url, String data, Callback<String, String> callback) {
        XMLHttpRequest request = new XMLHttpRequest();
        request.open("get", url);
        request.onreadystatechange = new XMLHttpRequest.OnreadystatechangeFn() {
            @Override
            public Object onInvoke(Event p0) {
                if (request.readyState == XMLHttpRequest.DONE) {
                    if (callback != null) {
                        if (request.status == 200) {
                            callback.onSuccess(request.responseText);
                        } else {
                            callback.onFailure(request.responseText);
                        }
                    }
                }
                return true;
            }
        };
        request.send(data);
    }
}
